
import { Base } from '../../utils/base.js';

class Cart extends Base {

  constructor(){
    super();

    this._storageKeyName = 'cart';
  }


  /*
    添加购物车
    如果商品不存在则添加一条新记录，数量为counts
    如果商品已经存在 则数量为原有数量 + counts
    @params
    item -{obj} 商品对象
    counts -{int} 商品数目
  */
  add(item, counts){
    var cartData = this.getCartDateFromLocal();
    var cartInfo = this._isHasThatOne(item.id, cartData);
    if(cartInfo.index == -1){
      item.counts = counts;
      item.selectStatus = true;  //设置商品选中状态
      cartData.push(item);
    }else{
      cartData[cartInfo.index].counts += counts;
    }
    wx.setStorageSync(this._storageKeyName, cartData);
  }

  //获取缓存中购物车商品的数据
  getCartDateFromLocal(flag){
    var res = wx.getStorageSync(this._storageKeyName);
    if(!res ){
      res = [];
    }

    if(flag){
      var newRes = [];
      for(let i=0; i<res.length; i++){
        if(res[i].selectStatus == true){
          newRes.push(res[i]);
        }
      }
      res = newRes;
    }

    return res;
  }

  //计算购物车内商品的总数量
  //flag 为 true 时，要考虑商品状态才计算数量
  getCartTotalCounts(flag){
    var data = this.getCartDateFromLocal();
    var counts = 0;

    for(let i=0; i<data.length; i++ ){
      if(flag){
        if(data[i].selectStatus){
          counts += data[i].counts;
        }
      }else{
        counts += data[i].counts;
      }
    }
    return counts;
  }

  //判断某个商品是否存在购物车中，并返回该商品的信息和所在数组中的序号
  _isHasThatOne(id , arr){
    var item,
      result = {index:-1};

    for( let i=0; i<arr.length; i++){
      item = arr[i];
      if(item.id == id){
        result = {
          index: i,
          data: item,
        }
        break;
      }
    }
    return result;
  }

  /* 
    修改商品数目
    @params
    id {int} 商品id
    counts {int} 商品数量
   */
  _changeCounts(id, counts){
    var cartData = this.getCartDateFromLocal(),
      hasInfo = this._isHasThatOne(id, cartData);
    
    if(hasInfo.index != -1){
      if(hasInfo.data.counts > 1 ){
        cartData[hasInfo.index].counts += counts;
      }
    }
    wx.setStorageSync(this._storageKeyName, cartData)
  }

  //增加商品数量
  addCounts(id){
    this._changeCounts(id, 1);
  }

  //减少商品数量
  cutCounts(id){
    this._changeCounts(id, -1);
  }

  //删除商品
  delete(ids) {
    if(!(ids instanceof Array)) {
      ids = [ids];
    }
    var cartData = this.getCartDateFromLocal();
    for(let i=0; i<ids.length; i++){
      var hasInfo = this._isHasThatOne(ids[i], cartData);
      if (hasInfo.index != -1) {
        cartData.splice(hasInfo.index, 1);
      }
    }
    wx.setStorageSync(this._storageKeyName, cartData)
  }

  //购物车的 更新保存。
  exeSetStorageSync(data){
    wx.setStorageSync(this._storageKeyName, data);
  }

}

export {Cart}